import { browser } from 'wxt/browser';
import {elmGetter} from '../../utils/elmgetter.js';
import {fetch,FormData} from 'node-fetch-native';
import ElementPlus from 'element-plus'
import VueDraggableResizable from 'vue-draggable-resizable'
import App from "./App.vue";
import { createApp } from "vue";
export default defineContentScript({
//   matches: ['*://10.10.21.28/gmp/static/sp/pt/instrumenttool/instrument/use/*'],
//   matches: ['*://10.10.21.28/gmp/static/sp/operationmanage/workticket/*'],
//   matches: ['*://10.10.21.28/gmp/static/sp/operationqualification/unifiedqualifications/personnelfiles/*'],
  matches: ['*://*/*'],
//   matches: ['*://10.10.21.28/gmp/static/sp/pt/instrumenttool/instrument/use/*','*://10.10.21.28/gmp/static/sp/operationmanage/workticket/*','*://10.10.21.28/gmp/static/sp/operationqualification/unifiedqualifications/personnelfiles/*'],
  allFrames:true,
  cssInjectionMode: "ui",
  async main(ctx) {
    const activetaburl =window.location.href;
    const toolsurl='http://10.10.21.28/gmp/static/sp/pt/instrumenttool/instrument/use/';
    const ticketurl='http://10.10.21.28/gmp/static/sp/operationmanage/operationticket/mainticket/mainTicketEdit.html';
    const all_flag=await localisenabletools.getValue();
    const flag1=await localisenabletool1.getValue();
    const flag2=await localisenabletool2.getValue();
    const flag3=await localisenabletool3.getValue();
    if(all_flag&&flag1&&activetaburl.startsWith(toolsurl)){
        
        elmGetter.get('[id="confirm"]').then(task =>{
            task.disabled=true;
        });
        const issubset=(arr1,arr2)=>{
            const noexist=[];
            arr2.forEach(item=>{
                if(!arr1.some(subitem=> subitem.includes(item))){
                    noexist.push(item);
                }
            });
            return noexist
        }
        const Plan_Nature=['生产类','非生产类'];
        const Work_Type=['预试','定检','巡视','检修','维护','消缺','操作','验收','安装更换','测量','带电','工器具试验','配合生产','其他生产','反措'];

        const Tool_list=[
            ['安全帽'],//预试
            ['安全帽'],//定检
            ['安全帽','测温','无人机',],//巡视
            ['安全帽'],//检修
            ['安全帽'],//维护
            ['安全帽'],//消缺
            ['安全帽','绝缘手套','绝缘棒',],//操作
            ['安全帽'],//验收
            ['安全帽'],//安装更换
            ['安全帽'],//测量
            ['安全帽'],//带电
            ['安全帽'],//工器具试验
            ['安全帽'],//配合生产
            ['安全帽'],//其他生产
            ['安全帽'],//反措
        ];
        let P_code='';
        const cz_button=elmGetter.create(`
        <button type="button" id="cz" class="c5-btn c5-btn-default" <span>检查</span> </button>
        `,document.getElementById('confirm').parentNode);//confirm
        cz_button.addEventListener('click',async e =>{
            let L_elm=[];
            let Wt=[];
            let StandardTool=[];
            elmGetter.each('[class="tag c5-top-widget "]',reply=>{
                L_elm.push(reply.innerText);
            });
            let Regex=/SCWH[0-9]+/;
            let P_codes=[];
            let SelectedTool=[];
            for (let i=0;i<L_elm.length;i++){
                if(Regex.test(L_elm[i])){
                    P_codes.push(L_elm[i]);
                } else{
                    SelectedTool.push(L_elm[i]);
                }
            }
            console.log(P_codes);
            console.log(SelectedTool);

            async function Getmess_fetch(){
                if(P_code!=''){
                    const params = {
                        "username": "ray123",
                        "password": 3,
                    };
                let P_data={
                    'provinceCode': "03", 
                    'bureauCode': "0352",
                    'bureauName': "揭阳供电局",
                    'orgLevel': "4",
                    'pageNo': '1',
                    'pageSize': '25',
                    'planBeginTime': "2024-01-01",
                    'planCode': P_code,
                    'planDateType': "month",
                    'planEndTime': "2024-12-31",
                    'planEndTimeDateRangePicker': ["2024-01-01", "2024-12-31"],
                    'provinceCode': "03",
                }
                const response = await fetch('http://10.10.21.28/gmp/sp/operationmaintenaceservice/prodplan/ppPlanQuery/queryPlanList', {
                    method: 'POST',
                    body: JSON.stringify(P_data),
                    headers: {'Content-Type': 'application/json'}
                })
                .then(response => response.text())
                .then(data => {
                    let res=JSON.parse(data).list[0];
                    if(res.planNature=='1'){
                        return res.workType;
                    }
                })
                return response
                }
        }
            async function Getpromiseandwait(){
                for (let i=0;i<P_codes.length;i++){
                    P_code=P_codes[i];
                    let work_type=await Getmess_fetch();
                    // let work_type=await Getmess();
                    console.log(work_type);
                    Wt.push(work_type);
                }
                for (let i=0;i<Wt.length;i++){
                    StandardTool=[...Tool_list[parseInt(Wt[i])-1],...StandardTool];
                }
                console.log(StandardTool);
                console.log(SelectedTool);
                let noexist_list=issubset(SelectedTool,StandardTool);
                if(noexist_list.length>0){
                    console.log("缺少工器具："+noexist_list);
                    alert("缺少工器具："+noexist_list);
                } else{
                    console.log('已领取所需工器具！');
                    alert('已领取所需工器具！');
                }
                elmGetter.get('[id="confirm"]').then(task =>{
                        task.disabled=false;
                });
            }
            Getpromiseandwait();
        });
    }
    if(all_flag&&flag2){
        const ticketurl = 'http://10.10.21.28/gmp/static/sp/operationmanage/workticket/standardticket';
        const queryurl = 'http://10.10.21.28/gmp/static/sp/operationqualification/unifiedqualifications/personnelfiles/OtherUnitOperatorArchiveList.html';
        
        // 定义要打开的网址和要在新标签页上运行的代码
        if(activetaburl.startsWith(ticketurl)){
            const querybut=document.createElement("button");
            querybut.type="button"
            querybut.innerHTML="查询资质";
            querybut.className="c5-btn";
            querybut.style.width="70px";
            querybut.style.height="60px";
            querybut.onclick=async function(e){
                const personstr=document.getElementById("workMemberUidDiv").querySelector("p").innerHTML;
                let namelist=personstr.split('、');
                const workleader=document.getElementById("workPrincipalUid").parentElement.querySelector("p").innerHTML
                const workticketname=document.getElementById("ticketSignUname").parentElement.querySelector("p").innerHTML
                namelist.push(workleader);
                namelist.push(workticketname);
                void localnamelist.setValue(namelist);
                const res=await browser.runtime.sendMessage('createtabs_tk');
                console.log(res);
            }
            let num=document.getElementById("workMemberCountDiv");
            num.parentElement.insertBefore(querybut,num)

        }
        if(activetaburl.startsWith(queryurl)){
            const nl=await localnamelist.getValue();
            for (var i=0;i<nl.length;i++){
                let name=document.createElement("button");
                name.type="button"
                name.innerHTML=nl[i];
                name.className="c5-btn";
                name.onclick=function(e){
                    var mybut=document.getElementsByClassName("query-filter-stop-propagation")[0];
                    let inputLabel = document.getElementById("userUname");
                    inputLabel.value = name.innerHTML;
                    inputLabel.dispatchEvent(
                        new Event("change", {
                            view: window,
                            bubbles: true,
                            cancelable: true,
                        })
                    );
                    mybut.click();
                }
                let reset=document.getElementById("btn-excel-export");
                reset.parentElement.insertBefore(name,reset)
            }

        }
    }
    // if(true){
    if(all_flag&&flag3&&activetaburl.startsWith(ticketurl)){
        const ui = await defineOverlay(ctx);
        // Mount initially
        ui.mount();
        // Re-mount when page changes
        ctx.addEventListener(window, "wxt:locationchange", (event) => {
        ui.mount();
        });
    }
  },
});
function defineOverlay(ctx) {
    return createShadowRootUi(ctx, {
      name: "vue-overlay",
      position: "overlay",
      anchor: "body",
      append: "before",
      zIndex: 9999,
      onMount(container, _shadow, shadowHost) {
        const app = createApp(App);
        app.use(ElementPlus,{zIndex: 1 });
        app.component("vue-draggable-resizable", VueDraggableResizable);
        app.mount(container);
        // shadowHost.style.pointerEvents = "none";
        return app;
      },
      onRemove(app) {
        app?.unmount();
      },
    });
  }
  